package xyz.shenmegui.foodcheckserver.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

@Component
public class PythonUtil {

    @Value("${crawler.command}")
    String command;
    @Value("${crawler.path}")
    String path;

    /**
     * python代码运行
     * @param name 文件名
     * @param values 参数
     * @return python代码中print的结果
     */
    public String Run(String name, String... values) {
        // 生成args
        int argsLength = values.length + 2;
        String[] args = new String[argsLength];
        args[0] = command;
        args[1] = path + name + ".py";
        System.arraycopy(values, 0, args, 2, argsLength - 2);
        // 运行
        StringBuilder result = new StringBuilder();
        try {
            Process process = Runtime.getRuntime().exec(args);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                result.append(line);
            }
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println("Python script executed successfully");
            } else {
                System.out.println("Python script execution failed");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.toString());
        }
        return result.toString();
    }
}
